
import path = require("path")
import fs = require("fs")
import express = require("express");
import { RoomModel } from "../hall_server/model/RoomModel";
import { Config } from "../src/config/Config";
import { DbConfig } from "../src/config/DbConfig";
import { ServerConfig } from "../src/config/ServerConfig";
import { SocketConnection } from "../src/engine/socketserver/socket/SocketConnection";
import { SocketConnectionManager } from "../src/engine/socketserver/socket/SocketConnectionManager";
import { Logger } from "../src/engine/utils/Logger";
import { TimerUtil } from "../src/engine/utils/TimerUtil";
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser')
const http = require("http");
// const ws = require("ws");
import { WebSocketServer } from 'ws';
import { mj_serverReqHandler } from "./mj_serverReqHandler";
/**
 */
export class mj_server {

    public static instance: mj_server = new mj_server()

    private initSocketServer() {
        Logger.log("initSocketServer==", ServerConfig.nowServerConfig)
        const wss = new WebSocketServer({
            port: ServerConfig.nowServerConfig.socket_port,
            perMessageDeflate: {
                zlibDeflateOptions: {
                    // See zlib defaults.
                    chunkSize: 1024,
                    memLevel: 7,
                    level: 3
                },
                zlibInflateOptions: {
                    chunkSize: 10 * 1024
                },
                // Other options settable:
                clientNoContextTakeover: true, // Defaults to negotiated value.
                serverNoContextTakeover: true, // Defaults to negotiated value.
                serverMaxWindowBits: 10, // Defaults to negotiated value.
                // Below options specified as default values.
                concurrencyLimit: 10, // Limits zlib concurrency for perf.
                threshold: 1024 // Size (in bytes) below which messages
                // should not be compressed if context takeover is disabled.
            },
            skipUTF8Validation:true
        });
        wss.on('connection', function connection(wsConnect, req) {
            let ip = req.headers['X-Real-IP'] || req.connection.remoteAddress
            if (ip && ip.indexOf('::ffff:') != -1) {
                ip = ip.substring(7);
            }
            let socketConn: SocketConnection = new SocketConnection(wsConnect, ip);
            SocketConnectionManager.instance.addSocketConnection(socketConn);
        });
        Logger.log("initSocketServer=22=", ServerConfig.nowServerConfig)
    }

    public async main() {
        let port: number = parseInt(process.argv[2]);
        if (isNaN(port)) {
            Logger.error("port为空")
            return;
        }
        let environment: number = parseInt(process.argv[3]);
        if (isNaN(port)) {
            Logger.warn("environment为空")
            return;
        }
        DbConfig.init(environment)
        Config.environment = environment;
        if (Config.environment == Config.EnvironmentType.Online) {
            // Logger.LEVEL = Logger.LOG_LEVEL_TYPES.WARN;
            Logger.LEVEL = Logger.LOG_LEVEL_TYPES.LOG
        } else {
            Logger.LEVEL = Logger.LOG_LEVEL_TYPES.LOG
        }
        Config.serverType = Config.ServerType_List.mj_server;
        Logger.tag = Config.serverType + "-" + port
        TimerUtil.init();
        await ServerConfig.initConfig(port)

        let app = express();
        let publicPath = path.resolve() + "/public";
        if (!fs.existsSync(publicPath)) {
            fs.mkdirSync(publicPath);
        }
        app.use(bodyParser.urlencoded({ extended: false })); //解析post请求数据
        app.use(bodyParser.text()); // for parsing application/json
        app.use(bodyParser.json()); // for parsing application/json

        //设置静态网页目录
        let options = {
            setHeaders: function (res, path, stat) {
                res.set('Access-Control-Allow-Origin', '*')
            }
        }
        app.disable('x-powered-by');
        app.use(express.static(publicPath, options));
        app.use(cookieParser())
        app.all('*', function (req, res, next) {
            req.header("Content-Type", "application/json;charset=UTF-8");
            res.header("Access-Control-Allow-Origin", "*");//项目上线后改成页面的地址
            res.header("Content-Type", "application/json;charset=UTF-8");
            res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
            next();
        });
        mj_serverReqHandler.instance.init(app)
        http.createServer(app).listen(port);
        this.initSocketServer()
        Logger.info("start suc=", ServerConfig.nowServerConfig);
    }
}

try {
    mj_server.instance.main()
    RoomModel.init();
    // SystemSettingModel.instance.init()
} catch (error) {
    Logger.info("error=", error)
    Logger.error("error=", error)
}